package com.algo.chat.server;

import java.net.SocketAddress;
import java.util.Iterator;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

public class ChatServerChannelHandler extends SimpleChannelInboundHandler<String> {
	
	private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
		Channel channel = ctx.channel();
		
		Iterator<Channel> channelInterator = channelGroup.iterator();
		while (channelInterator.hasNext()) {
			Channel remoteChannel = channelInterator.next();
			if (channel != remoteChannel) {
				remoteChannel.writeAndFlush("[客户端" + channel.remoteAddress() + "]：" + msg);
			}
		}
	}
	
    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
       Channel channel = ctx.channel();
       SocketAddress socketAddress = channel.remoteAddress();
       System.out.println("客户端" + socketAddress + "准备上线");
    }
    
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
    	Channel channel = ctx.channel();
        SocketAddress socketAddress = channel.remoteAddress();
        System.out.println("客户端" + socketAddress + "完成上线");
        
        channelGroup.add(channel);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    	Channel channel = ctx.channel();
        SocketAddress socketAddress = channel.remoteAddress();
        System.out.println("客户端" + socketAddress + "正在下线");
    }
    
    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
    	Channel channel = ctx.channel();
        SocketAddress socketAddress = channel.remoteAddress();
        System.out.println("客户端" + socketAddress + "完成下线");
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
    	cause.printStackTrace();
    	ctx.channel().close();
    }
    

}
